require('dotenv-flow').config();
const {name} = require('../../package.json');
const exec = require('shelljs.exec');
const logger = require('../libs/logger');
const env = require('@blocklet/sdk/lib/env');

async function createSqliteDatabase() {
  const schemaUrl = process.cwd() + '/prisma/schema.prisma'

  // 注意: npx 可能会运行一个被缓存的旧版本的 prisma, 所以建议在这里为 prisma 指定 "latest" 或一个特定版本号
  exec(`prisma generate --schema ${schemaUrl}`);

  logger.log('DATABASE_URL is ' + process.env.DATABASE_URL)
  if (process.env.DATABASE_URL) {
    return;
  }

  process.env.DATABASE_URL = `file:${env.dataDir}'/db/line.db')}`;

  logger.log('DATABASE_URL is ' + process.env.DATABASE_URL)

  // @see: https://www.prisma.io/docs/concepts/components/prisma-migrate/db-push#can-i-use-prisma-migrate-and-db-push-together
  exec(`prisma migrate deploy --schema ${schemaUrl}`);
}

(async () => {
  try {
    await createSqliteDatabase();
  } catch (err) {
    logger.error(`${name} pre-install error`, err.message);
    process.exit(1);
  }
})();
